﻿using GenerateProtocol.Helper;
using GenerateProtocol.Models;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace GenerateProtocol
{
    public class ProtocolGenerate
    {
        private SqlSugarClient _sqlSugarClient;

        public ProtocolGenerate() { }

        public ProtocolGenerate(SqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        public string ScriptProtocolGenerate(int itemId)
        {
            var supespaceitem = new SupeSpaceitems();
            try
            {
                // 获取稿件信息
                supespaceitem = _sqlSugarClient.Queryable<SupeSpaceitems>().Single(x => x.itemid == itemId);
                if (supespaceitem == null || supespaceitem.isscan == true)
                {
                    return null;
                }

                var haveAttachment = supespaceitem.picid > 0;
                var attachment = new SupeAttachments();
                if (haveAttachment)
                {
                    // 获取稿件中包含的附件
                    attachment = _sqlSugarClient.Queryable<SupeAttachments>().Single(x => x.aid == supespaceitem.picid);
                }
                // 获取稿件内容
                var supespacenew = _sqlSugarClient.Queryable<SupeSpacenews>().Single(x => x.itemid == itemId);

                // 生成统一guid
                //var guid = Extension.GetMd5Hash(Convert.ToString(supespaceitem.itemid)); // itemid可能与picid重复，导致素材与稿件contentid重复入库失败
                var guid = Guid.NewGuid().ToString("N");
                string picContentId = string.Empty;
                #region 文稿s6v2协议 构建
                var uep = new UnifiedExchangeProtocol();

                #region Head
                var head = new HeadType();
                head.TaskCurrentGUID = guid;
                head.TaskName = supespaceitem.subject;
                uep.Head = head;
                #endregion

                #region ContentInfo 构建
                var contentInfo = new FullContentDataType();
                contentInfo.ContentID = guid;
                contentInfo.TypeID = "biz_sobey_script";
                contentInfo.TypeName = "文稿";

                #region ContentData 构建
                var contentData = new ContentDataType();

                #region EntityData 构建
                var EntityDataList = new List<AttributeItemType>();
                Extension.AddAttributeItemType(EntityDataList, "clipname", supespaceitem.subject, string.Empty, true);
                Extension.AddAttributeItemType(EntityDataList, "loginname", "10001001", string.Empty, true);
                Extension.AddAttributeItemType(EntityDataList, "reportperson", supespaceitem.reportperson, "报题人", true);
                Extension.AddAttributeItemType(EntityDataList, "keyword", supespaceitem.keywords, string.Empty, true);
                Extension.AddAttributeItemType(EntityDataList, "journallist", supespaceitem.reportperson, string.Empty, true);
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区  
                var time = startTime.AddSeconds(supespaceitem.dateline).ToString("yyyy-MM-dd HH:mm:ss");
                Extension.AddAttributeItemType(EntityDataList, "StoragedDate", time, string.Empty, true);
                if (haveAttachment)
                {
                    picContentId = Extension.GetMd5Hash(Convert.ToString(supespaceitem.picid));
                    Extension.AddAttributeItemType(EntityDataList, "relationIds", picContentId, "附件关联contentid", true);
                }
                #endregion
                contentData.EntityData = EntityDataList.ToArray();
                #endregion

                #region metadata.content 构建

                var metaDataList = new List<MetaDataDefineDataType>();
                var SmetaData = new MetaDataDefineDataType();
                SmetaData.TypeID = ClipTypeHive.biz_sobey_script.ToString();
                SmetaData.TypeName = "文稿";
                var SattributesTypeList = new List<AttributesType>();
                var SattributesType = new AttributesType();
                var SattributeItemList = new List<AttributeItemType>();
                Extension.AddAttributeItemType(SattributeItemList, "content", HttpUtility.HtmlEncode(supespacenew.message), "内容", true);
                SattributesType.AttributeItem = SattributeItemList.ToArray();
                SattributesTypeList.Add(SattributesType);
                SmetaData.Attributes = SattributesTypeList.ToArray();
                metaDataList.Add(SmetaData);
                contentInfo.MetaData = metaDataList.ToArray();

                #endregion


                #region 附件MetaData 构建
                if (haveAttachment)
                {
                    var RmetaData = new MetaDataDefineDataType();
                    RmetaData.TypeID = "relations";
                    RmetaData.TypeName = "关系";
                    var RattributesTypeList = new List<AttributesType>();
                    var RattributesType = new AttributesType();
                    var RattributeItemList = new List<AttributeItemType>();
                    Extension.AddAttributeItemType(RattributeItemList, "relType", Extension.GetEntityType(attachment.filepath), "关系类型", true);
                    Extension.AddAttributeItemType(RattributeItemList, "relFieldName", "contentid", "关联字段", true);
                    Extension.AddAttributeItemType(RattributeItemList, "relFieldValue", picContentId, "关联值", true);
                    Extension.AddAttributeItemType(RattributeItemList, "loginname", "10001001", string.Empty, true);
                    RattributesType.AttributeItem = RattributeItemList.ToArray();
                    RattributesTypeList.Add(RattributesType);
                    RmetaData.Attributes = RattributesTypeList.ToArray();
                    metaDataList.Add(RmetaData);
                    contentInfo.MetaData = metaDataList.ToArray();

                    // 附件协议 构建
                    AttachmentProtocolGennrate(supespaceitem.picid);
                }
                #endregion

                contentInfo.ContentData = contentData;
                uep.ContentInfo = contentInfo;
                #endregion

                #endregion

                string xmlStr = XMLHelper.Object2Xml(uep, typeof(UnifiedExchangeProtocol), false).Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
                string currentDirectory = Directory.GetCurrentDirectory();
                string xmlPath = Path.Combine(currentDirectory, "upload/scriptxmlprotocol", $"{guid}.xml").Replace("\\", "/");
                var parent = Directory.GetParent(xmlPath);
                if (parent != null && !Directory.Exists(parent.FullName))
                {
                    Directory.CreateDirectory(parent.FullName);
                }
                if (!File.Exists(xmlPath))
                {
                    File.WriteAllText(xmlPath, xmlStr);
                }
                supespaceitem.isscan = true;
                var updateResult = _sqlSugarClient.Updateable(supespaceitem).WhereColumns(x => new { x.itemid }).UpdateColumns(x => new { x.isscan }).ExecuteCommand();
                return xmlStr;
            }
            catch (Exception ex)
            {
                supespaceitem.isscan = false;
                var updateResult = _sqlSugarClient.Updateable(supespaceitem).WhereColumns(x => new { x.itemid }).UpdateColumns(x => new { x.isscan }).ExecuteCommand();
                return ex.ToString();
            }
        }

        public string AttachmentProtocolGennrate(int picId)
        {
            var attachment = new SupeAttachments();
            try
            {
                attachment = _sqlSugarClient.Queryable<SupeAttachments>().Single(x => x.aid == picId);
                var picContentId = Extension.GetMd5Hash(Convert.ToString(picId));

                #region 附件协议 构建
                var uep = new UnifiedExchangeProtocol();
                #region Head
                var head = new HeadType();
                head.TaskCurrentGUID = picContentId;
                head.TaskName = attachment.subject;
                uep.Head = head;
                #endregion

                #region ContentInfo 构建
                var contentInfo = new FullContentDataType();
                contentInfo.ContentID = picContentId;
                contentInfo.TypeID = Extension.GetEntityType(attachment.filepath);
                contentInfo.TypeName = "文稿";

                #region ContentData 构建
                var contentData = new ContentDataType();

                #region EntityData 构建
                var EntityDataList = new List<AttributeItemType>();
                Extension.AddAttributeItemType(EntityDataList, "clipname", attachment.subject, string.Empty, true);

                #endregion

                contentData.EntityData = EntityDataList.ToArray();
                #endregion

                #region ContentFile 构建
                var contentFile = new ContentFileType();
                var fileItemList = new List<FileItemType>();
                var fileItem = new FileItemType();
                fileItem.FileGUID = Guid.NewGuid().ToString("N");
                var fileItemTypeFileName = new FileItemTypeFileName();
                fileItemTypeFileName.FullPath = attachment.filepath;
                fileItem.FileName = fileItemTypeFileName;
                fileItemList.Add(fileItem);
                contentFile.FileItem = fileItemList.ToArray();
                contentData.ContentFile = contentFile;
                #endregion

                contentInfo.ContentData = contentData;
                uep.ContentInfo = contentInfo;
                #endregion

                #endregion
                string xmlStr = XMLHelper.Object2Xml(uep, typeof(UnifiedExchangeProtocol), false).Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");

                // xml协议写入文件
                string currentDirectory = Directory.GetCurrentDirectory();
                string tempPath = Path.Combine(currentDirectory, "upload", attachment.filepath).Replace("\\", "/");
                var fileName = Path.GetFileName(tempPath);
                var xmlPath = Path.ChangeExtension(tempPath, ".xml");

                var parent = Directory.GetParent(xmlPath);

                if (parent != null && !Directory.Exists(parent.FullName))
                {
                    Directory.CreateDirectory(parent.FullName);
                }
                if (!File.Exists(xmlPath))
                {
                    File.WriteAllText(xmlPath, xmlStr);
                }
                attachment.isscan = true;
                var updateResult = _sqlSugarClient.Updateable(attachment).WhereColumns(x => new { x.aid }).UpdateColumns(x => new { x.isscan }).ExecuteCommand();
                return xmlStr;
            }
            catch (Exception ex)
            {
                attachment.isscan = false;
                var updateResult = _sqlSugarClient.Updateable(attachment).WhereColumns(x => new { x.aid }).UpdateColumns(x => new { x.isscan }).ExecuteCommand();
                return ex.ToString();
            }
        }
    }
}
